package com.star.star.service.impl;

import cn.hutool.core.lang.Assert;
import com.star.star.contants.StarRedis;
import com.star.star.entity.StarSupport;
import com.star.star.entity.StarSupport;
import com.star.star.entity.StarSupport;
import com.star.star.mapper.StarSupportMapper;
import com.star.star.service.StarService;
import com.star.star.service.StarSupportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 艺人支持 服务实现类
 *
 * @author yangzj
 */
@Service
public class StarSupportServiceImpl extends ServiceImpl<StarSupportMapper, StarSupport> implements StarSupportService {

    @Autowired
    private StarService starService;
    @Autowired
    private RedissonClient redisson;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrDelete(Long starId, boolean support, Long userId) {
        RLock lock = redisson.getLock(StarRedis.SUPPORT_LOCK + starId);
        try {
            lock.lock();
            if (support) {
                boolean exists = this.lambdaQuery().eq(StarSupport::getStarId, starId).eq(StarSupport::getUserId, userId).exists();
                Assert.isFalse(exists, "已支持");
                this.save(new StarSupport().setStarId(starId).setUserId(userId));
                starService.incrementSupportCount(starId, true);
            } else {
                // 取消支持
                boolean remove = this.lambdaUpdate().eq(StarSupport::getStarId, starId).eq(StarSupport::getUserId, userId).remove();
                if (remove) {
                    starService.incrementSupportCount(starId, false);
                }
            }
        } finally {
            lock.unlock();
        }
    }
}
